/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package almacen;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import resources.local_connection;

/**
 *
 * @author pato
 */
public class transferirEspeciales extends javax.swing.JFrame {

    /**
     * Creates new form transferirEspeciales
     */
    PreparedStatement ps;
    ResultSet rs;
    String tipo;
    int codigo, suc1, suc2;
    private final DefaultListModel modelo1;
    private final DefaultListModel modelo2;
    Vector sucursales= new Vector();
    ArrayList<String> datos1 = new ArrayList<>();
    ArrayList<String> datos2 = new ArrayList<>();
    public transferirEspeciales(String t, int c, int s1, int s2) {
        initComponents();
        aceptar.setVisible(false);
        modelo1 = new DefaultListModel();
        listaSuc1.setModel(modelo1);
        modelo2 = new DefaultListModel();
        listaSuc2.setModel(modelo2);
       // Vector sucursales = new Vector();
        codigo = c;
        tipo = t;
        suc1 = s1;
        suc2 = s2;
        cargarDatos();
        cargarSucursales();
    }
private void cargarSucursales() {
        try {
            ps = local_connection.getconnect().prepareStatement("select nombre, id from sucursales where activo = 1");
            rs = ps.executeQuery();
            while (rs.next()) {
                sucursal1.addItem(rs.getString(1));
                sucursal2.addItem(rs.getString(1));
                sucursales.add(rs.getInt(2));
            }
            sucursal1.setSelectedIndex(sucursales.indexOf(suc1));
            sucursal2.setSelectedIndex(sucursales.indexOf(suc2));
        } catch (SQLException ex) {
Almacen.logger.log(Level.SEVERE, null, ex);        }
    }
    private void cargarDatos() {
        modelo1.clear();
        modelo2.clear();
        buscador1.setText("");
        buscador2.setText("");
        try {
            ps=local_connection.getconnect().prepareStatement("select nombre from productos where id_producto = ?");
            ps.setInt(1,codigo);
            rs=ps.executeQuery();
            if(rs.next())
                super.setTitle(codigo+"-"+rs.getString(1));
          
            String idprod = ("Chip".equals(tipo)) ? "" : " and id_producto=" + codigo;
            ps = local_connection.getconnect().prepareStatement("select clave, sucursal from especiales where vendido=0 and tipo=?" + idprod + " and (sucursal = ? or sucursal = ?)");
            ps.setString(1, tipo);
            ps.setInt(2, suc1);
            ps.setInt(3, suc2);
            rs = ps.executeQuery();
            while (rs.next()) {
                if (rs.getInt("sucursal") == suc1) {
                    modelo1.addElement(rs.getString("clave"));
                    datos1.add(rs.getString("clave"));
                } else {
                    modelo2.addElement(rs.getString("clave"));
                    datos2.add(rs.getString("clave"));
                }

            }
        } catch (SQLException ex) {
Almacen.logger.log(Level.SEVERE, null, ex);        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        listaSuc1 = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        listaSuc2 = new javax.swing.JList();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        aceptar = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        sucursal1 = new javax.swing.JComboBox();
        sucursal2 = new javax.swing.JComboBox();
        buscador1 = new javax.swing.JTextField();
        buscador2 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);

        jScrollPane1.setViewportView(listaSuc1);

        jScrollPane2.setViewportView(listaSuc2);

        jButton1.setText(">>");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("<<");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        aceptar.setText("Aceptar");
        aceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                aceptarActionPerformed(evt);
            }
        });

        jButton4.setText("Cerrar");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        sucursal1.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
            public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) {
            }
            public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
                sucursal1PopupMenuWillBecomeInvisible(evt);
            }
            public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
            }
        });

        sucursal2.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
            public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) {
            }
            public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
                sucursal2PopupMenuWillBecomeInvisible(evt);
            }
            public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
            }
        });

        buscador1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                buscador1KeyReleased(evt);
            }
        });

        buscador2.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                buscador2KeyReleased(evt);
            }
        });

        jLabel1.setText("Buscar:");

        jLabel2.setText("Buscar:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 314, Short.MAX_VALUE)
                        .addComponent(aceptar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(buscador1)
                                    .addComponent(sucursal1, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 197, Short.MAX_VALUE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jButton1)
                                    .addComponent(jButton2)))
                            .addComponent(jLabel1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(buscador2)
                                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 200, Short.MAX_VALUE)
                                .addComponent(sucursal2, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(sucursal1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(sucursal2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buscador1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(buscador2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 242, Short.MAX_VALUE)
                    .addComponent(jScrollPane2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(aceptar)
                    .addComponent(jButton4)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        this.dispose();
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        if (!listaSuc1.isSelectionEmpty()) {
            String clave;
            List<String> claves = listaSuc1.getSelectedValuesList();
            for (String clave1 : claves) {
                try {
                    clave = clave1;
                    modelo1.removeElement(clave);
                    modelo2.addElement(clave);
                    ps = local_connection.getconnect().prepareStatement("update especiales set sucursal = ? where clave = ?");
                    ps.setInt(1,suc2);
                    ps.setString(2, clave);
                    ps.execute();
                    ps= local_connection.getconnect().prepareStatement("update stock set cantidad = cantidad+1 where sucursal = ? and id_producto = ?");
                    ps.setInt(1,suc2);
                    ps.setInt(2,codigo);
                    ps.execute();
                    ps= local_connection.getconnect().prepareStatement("update stock set cantidad = cantidad-1 where sucursal = ? and id_producto = ?");
                    ps.setInt(1,suc1);
                    ps.setInt(2,codigo);
                    ps.execute();
                } catch (SQLException ex) {
                    Almacen.logger.log(Level.SEVERE, null, ex);
                }
                        
            }
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        if (!listaSuc2.isSelectionEmpty()) {
            String clave;
            List<String> claves = listaSuc2.getSelectedValuesList();
            for (String clave1 : claves) {
                try {
                    clave = clave1;
                    modelo2.removeElement(clave);
                    modelo1.addElement(clave);
                    ps = local_connection.getconnect().prepareStatement("update especiales set sucursal = ? where clave = ?");
                    ps.setInt(1,suc1);
                    ps.setString(2, clave);
                    ps.execute();
                    ps= local_connection.getconnect().prepareStatement("update stock set cantidad = cantidad+1 where sucursal = ? and id_producto = ?");
                    ps.setInt(1,suc1);
                    ps.setInt(2,codigo);
                    ps.execute();
                    ps= local_connection.getconnect().prepareStatement("update stock set cantidad = cantidad-1 where sucursal = ? and id_producto = ?");
                    ps.setInt(1,suc2);
                    ps.setInt(2,codigo);
                    ps.execute();
                } catch (SQLException ex) {
                    Logger.getLogger(transferirEspeciales.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton2ActionPerformed

    private void aceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aceptarActionPerformed
        String consulta;
        int i;
        try {
            if (!modelo1.isEmpty()) {
                consulta = "";
                for ( i = 0; i < modelo1.size(); i++) {
                    consulta += (i > 0) ? " or clave='" + modelo1.getElementAt(i) + "'" : "clave='" + modelo1.getElementAt(i) + "'";
                }
              //  if(tipo.equals("Celular")){
                ps=local_connection.getconnect().prepareStatement("insert into stock(id_producto,sucursal,cantidad) values (?,?,?) ON DUPLICATE KEY UPDATE cantidad=(?)");
                ps.setInt(1,codigo);
                ps.setInt(2,suc1);
                ps.setInt(3,i);
                ps.setInt(4,i);
                ps.execute();
               // }
                ps = local_connection.getconnect().prepareStatement("update especiales set sucursal = ? where "+consulta);
                ps.setInt(1,suc1);
                ps.execute();
            }
            else {
                 ps=local_connection.getconnect().prepareStatement("insert into stock(id_producto,sucursal,cantidad) values (?,?,?) ON DUPLICATE KEY UPDATE cantidad=(?)");
                ps.setInt(1,codigo);
                ps.setInt(2,suc1);
                ps.setInt(3,0);
                ps.setInt(4,0);
                ps.execute();
                
            }
            if (!modelo2.isEmpty()) {
                consulta = "";
                for ( i = 0; i < modelo2.size(); i++) {
                    consulta += (i > 0) ? " or clave='" + modelo2.getElementAt(i) + "'" : "clave='" + modelo2.getElementAt(i) + "'";
                }
             //   if(tipo.equals("Celular")){
                ps=local_connection.getconnect().prepareStatement("insert into stock(id_producto,sucursal,cantidad) values (?,?,?) ON DUPLICATE KEY UPDATE cantidad=(?)");
                ps.setInt(1,codigo);
                ps.setInt(2,suc2);
                ps.setInt(3,i);
                ps.setInt(4,i);
                ps.execute();
              //  }
                ps = local_connection.getconnect().prepareStatement("update especiales set sucursal = ? where "+consulta);
                ps.setInt(1,suc2);
                ps.execute();
            }
             else {
                 ps=local_connection.getconnect().prepareStatement("insert into stock(id_producto,sucursal,cantidad) values (?,?,?) ON DUPLICATE KEY UPDATE cantidad=(?)");
                ps.setInt(1,codigo);
                ps.setInt(2,suc2);
                ps.setInt(3,0);
                ps.setInt(4,0);
                ps.execute();
                
            }
        } // TODO add your handling code here:
        catch (SQLException ex) {
Almacen.logger.log(Level.SEVERE, null, ex);        }
        this.dispose();

    }//GEN-LAST:event_aceptarActionPerformed

    private void sucursal1PopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_sucursal1PopupMenuWillBecomeInvisible
        suc1=(int) sucursales.get(sucursal1.getSelectedIndex());
        cargarDatos();
        // TODO add your handling code here:
    }//GEN-LAST:event_sucursal1PopupMenuWillBecomeInvisible

    private void sucursal2PopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_sucursal2PopupMenuWillBecomeInvisible
        suc2=(int) sucursales.get(sucursal2.getSelectedIndex());
        cargarDatos();
        // TODO add your handling code here:
    }//GEN-LAST:event_sucursal2PopupMenuWillBecomeInvisible

    private void buscador1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_buscador1KeyReleased
        modelo1.clear();
        for (String datos11 : datos1) {
            if (datos11.contains(buscador1.getText())) {
                modelo1.addElement(datos11);
            }
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_buscador1KeyReleased

    private void buscador2KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_buscador2KeyReleased
modelo2.clear();
        for (String datos11 : datos2) {
            if (datos11.contains(buscador2.getText())) {
                modelo2.addElement(datos11);
            }
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_buscador2KeyReleased

    /**
     * @param args the command line arguments
     */

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton aceptar;
    private javax.swing.JTextField buscador1;
    private javax.swing.JTextField buscador2;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JList listaSuc1;
    private javax.swing.JList listaSuc2;
    private javax.swing.JComboBox sucursal1;
    private javax.swing.JComboBox sucursal2;
    // End of variables declaration//GEN-END:variables
}
